package com.exam.service.impl;

import com.exam.dao.ExamDao;
import com.exam.dao.QuestionDao;
import com.exam.dao.RecordDao;
import com.exam.dao.StudentDao;
import com.exam.domain.entity.*;
import com.exam.service.StudentService;
import com.exam.util.BaseResult;

import java.util.List;
import java.util.Objects;

public class StudentServiceImpl implements StudentService {

    private final StudentDao studentDao;
    private final QuestionDao questionDao;
    private final ExamDao examDao;
    private final RecordDao recordDao;

    public StudentServiceImpl() {
        this.studentDao = new StudentDao();
        this.questionDao = new QuestionDao();
        this.examDao = new ExamDao();
        this.recordDao = new RecordDao();
    }

    @Override
    public BaseResult<Student> getStudentInfoByStudentId(Integer studentId) {
        // 从user表中查询学生的基本信息
        Student student = studentDao.getStudentInfoByStudentId(studentId);
        //
        return BaseResult.success(student);
    }

    @Override
    public BaseResult<List<Exam>> getExamList(Integer studentId) {
        // 获得激活的试卷列表，通过创建时间...
        List<Exam> exams = studentDao.getExamListWhichActive();
        for (Exam exam : exams) {
            // 如果这场考试学生已经参加过了，则，标记已参加，不可以再重复参加。
            Integer examId = exam.getExamId();
            // 获取学生的考试记录，查询是否已经参加过该考试
            Record record = recordDao.getStudentExamRecord(examId,studentId);
            if(Objects.isNull(record)){
                exam.setIsSubmit(0);
            }else {
                exam.setIsSubmit(1);
            }
        }
        return BaseResult.success(exams);
    }

    @Override
    public BaseResult<String> submitExam(Integer studentId, Integer examId, List<Answer> answers) {
        // 提交考试，和答案。
        // 计算总得分
        Integer totalScore = 0;
        Record record = new Record();
        for (Answer answer:answers){
            Integer questionId = answer.getQuestionId();
            String selectedOption = answer.getSelectedOption();
            // 对比被选选项和正确答案
            Question question = questionDao.getQuestionById(questionId);
            // 如果回答正确了，设置该题的得分
            if(selectedOption.equals(question.getCorrectOption())){
                // 设置该题的得分。
                Exam exam = examDao.getExamInfoById(examId);
                answer.setScore(exam.getScorePerQuestion());
                totalScore+=exam.getScorePerQuestion();
            }else{
                // 回答错误
                answer.setScore(0);
            }
        }
        record.setExamId(examId);
        record.setTotalScore(totalScore);
        record.setStudentId(studentId);
        // 提交试卷，先插入考试记录表：exam_records学生的考试记录，然后根据插入的数据获取record_id，然后插入到student_answers表中：
        studentDao.submitExamRecordAndStudentAnswer(record,answers);
        return BaseResult.success("提交试卷成功");
    }
}
